package com.fix.websocket;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.fix.entity.Message;
import com.fix.entity.Users;
import com.fix.util.MyDateFormat;
import com.google.gson.Gson;

/**
 * 消息处理器
 * 
 * @author fix
 *
 */
@Component
public class ChatWebSocketHandler implements WebSocketHandler {

	Gson json = new Gson();
	// 存储在线用户
	public static final Map<String, WebSocketSession> USER_MAP;

	static {
		USER_MAP = new HashMap<String, WebSocketSession>();
	}

	/**
	 * 连接成功时候，会触发页面上onopen方法
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession socketSession) throws Exception {
		// 从socketSession 取出登录用户信息
		Users user = (Users) socketSession.getAttributes().get("socketuser");
		// 新用户放入 map里
		USER_MAP.put(user.getUid(), socketSession);

		Message msg = new Message();
		String now = MyDateFormat.parse(new Date());
		msg.setDate(now);
		msg.setText("[" + user.getuName() + "]来了。。。大家欢迎！");

		TextMessage text = new TextMessage(json.toJson(msg));
		// 群发消息告诉大家
		sendToAll(text);
	}

	/**
	 * js调用websocket.send时候，会调用该方法
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		if (message.getPayloadLength() == 0) // 消息长度=0
			return;
		
		String obj = message.getPayload().toString();
		Message msg =json.fromJson(obj, Message.class);
		msg.setDate( MyDateFormat.parse(new Date()) );
		TextMessage text = new TextMessage(json.toJson(msg));
		System.out.println("收到消息...."+ json.toJson(msg));
		// 判断是群发是单发
		if ( msg.getTo() == null || msg.getTo().equals("-1")) {
			sendToAll( text );
		}else {
			sendToOne(msg.getTo(), text);
		}
	}

	/**
	 * 出现异常
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		// TODO Auto-generated method stub

	}

	/**
     * 关闭连接时触发
     * 把用户从 map 里删除
     */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		Users user = (Users) session.getAttributes().get("socketuser");
		USER_MAP.remove(user.getUid());
		System.out.println( user.getuName()+"用户下线了"+USER_MAP);

	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

	// 群发消息
	public void sendToAll(TextMessage info) {
		Set<String> keys = USER_MAP.keySet();
		for (String k : keys) {
			WebSocketSession socketSession = USER_MAP.get(k);
			if (socketSession.isOpen()) {
				new Thread(new Runnable() { // 开线程发消息
					public void run() {
						try {
							socketSession.sendMessage(info);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}).start();
			}
		}
	}

	// 群发消息
	public void sendToOne(String userId , TextMessage info) throws IOException { 
		WebSocketSession socketSession = USER_MAP.get(userId);
		if (socketSession!=null && socketSession.isOpen()) {
			 socketSession.sendMessage(info); 
		}
	}

}
